from flask import Flask,request,jsonify
from flask_cors import CORS
import logging
from logging import FileHandler
import datetime
from views.comany import bp_company
from views.users import bp_user
from utils.jwtc import myjwt
from utils.rs import rs





# app = Flask(__name__)
def create_app():
    app = Flask(__name__)
    with app.app_context():
        pass
    return app
app = create_app()

app.register_blueprint(bp_company)
app.register_blueprint(bp_user)
CORS(app)


@app.before_request
def before_request():
    # 定义白名单
    white = ['/login']
    if request.path not in white:
        # 401过期 403标识没获取token
        try:
            token = request.headers['Token']
        except:
            return jsonify({'code':403,'mes':'无权访问'})
    
    # 调用decode解析token
    if myjwt.jwt_check(token) == Flask:
        return jsonify({'code':402,'msg':'token不合法'})
    # 权限验证
    payload = myjwt.jwt_de(token)
    uid = payload['data']['userid']
    key = 'interface'+str(uid)
    # # 根据用户id获取接口权限
    list = rs.find_set(key)
    if request.path not in list:
        return jsonify({'code':40301,'mes':'无权访问'})






if __name__ == "__main__":
    filename = datetime.datetime.strftime(datetime.datetime.now(),'%Y%m')
    handler = logging.FileHandler('logs/'+filename+'.txt')
    app.logger.addHandler(handler)
    app.run(debug=True)